package com.xpgk.mvc.measurement;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.apache.commons.codec.binary.Base64;

import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.xpgk.annotation.Service;
import com.xpgk.constant.ConstantRender;
import com.xpgk.dto.RenderBean;
import com.xpgk.mvc.base.BaseService;
import com.xpgk.mvc.bentryRegister.BentryRegisterService;
import com.xpgk.mvc.bentryRegister.Customer;
import com.xpgk.mvc.bentryRegister.CustomerAgreement;
import com.xpgk.mvc.bentryRegister.CustomerDetail;
import com.xpgk.mvc.bloseWeight.DelWeiTargetSum;
import com.xpgk.mvc.codeSet.Code;
import com.xpgk.mvc.organization.Organization;
import com.xpgk.mvc.productPrice.Price;
import com.xpgk.mvc.productPrice.ProductPrice;
import com.xpgk.mvc.scallVisit.ScallVisit;
import com.xpgk.mvc.statistic.dailyTotalStatistic.DailyNursingTotal;
import com.xpgk.mvc.statistic.monthTotalStatistic.MonthTotal;
import com.xpgk.mvc.statistic.yearTotalStatistic.YearTotal;
import com.xpgk.tools.ToolDateTime;
import com.xpgk.tools.ToolRandoms;
import com.xpgk.tools.security.ToolPbkdf2;

@Service(name = TemporaryServices.serviceName)
public class TemporaryServices extends BaseService {

	public static final String serviceName = "temporaryService";

	@SuppressWarnings("unused")
	private static final Log log = Log.getLog(TemporaryServices.class);

	/**
	 * 查询编号
	 */
	public String getNumber(String organids) {
		// 获取当月
		SimpleDateFormat df = new SimpleDateFormat("yyMM");
		String date = df.format(new Date());
		// 获取当前代理商门店编号
		Record r=Db.findFirst("SELECT IFNULL(substring(number,5),0)  n  from sb_customer_temporary WHERE organIds =?  ORDER BY   substring(number,5) DESC LIMIT 1",organids);
		int a = 0;
		if(r!=null){
			a =Integer.parseInt(r.getStr("n"));
		}
		return  date + String.format("%03d", a + 1);
	}

	/**
	 * 保存测算数据
	 */
	public Map<String, Object> saveRecord(Temporary temp, String organids) {

		String msg = ConstantRender.render_success_code;
		Map<String, Object> mm = new HashMap<>();
		if (temp != null) {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("column", Customer.column_phone);
			String sql = getSqlByBeetl(Customer.sqlId_column, param);
			Customer cus = Customer.dao.findFirst(sql, temp.getStr(Temporary.column_phone));
			if (cus != null) {
				// 已成交顾客
				log.debug("该顾客已为成交顾客，无需再次测算！！");
				// msg="测算信息保存失败！！";
				// throw new RuntimeException("该顾客已为成交顾客，不需要再次测算!");
				msg = "该顾客已为成交顾客，无需再次测算！！";
			} else {
				// 未成交顾客
				float stdWeight = getStdWeight(temp.getStr("sex"), temp.getInt("height"), temp.getInt("age"));
				if (stdWeight != 0) {
					mm.put("stdWeight", stdWeight);
					DecimalFormat decimalFormat = new DecimalFormat(".0");
					float delWeight = temp.getFloat(Temporary.column_weight) - stdWeight;
					mm.put("delWeight", decimalFormat.format(delWeight));
					int treatment = getTreatment(Float.parseFloat(decimalFormat.format(delWeight)));
					mm.put("goal", treatment);
					
					Organization organization = Organization.dao.findById(organids);
					String dlsIds = organization.getStr(Organization.column_parentIds);
					String sqlPriceIds = "SELECT * FROM sb_shop_price where organizationIds = ?";
					Price price = Price.dao.findFirst(sqlPriceIds,dlsIds);
					String priceIds = price.getStr(Price.column_ids);
					String sqlProductPrice = "SELECT * FROM sb_product_price where priceIds = ? and productIds = ? and status = '1'";
					
					float bzlc = ProductPrice.dao.findFirst(sqlProductPrice,priceIds,Code.bzlc_ids).getFloat("outPrice");
					float ylc = ProductPrice.dao.findFirst(sqlProductPrice,priceIds,Code.ylcdsh_ids).getFloat("outPrice");
					if (treatment == 1) {
						mm.put("cost", ylc);
					} else {
						mm.put("cost", treatment * bzlc);
					}
					Temporary oldTemp = Temporary.dao.getTodayRecord(temp.getStr(Temporary.column_phone));
					if (oldTemp != null) {
						temp.set("treatment", treatment).set("ids", oldTemp.getStr("ids")).set("gxsj", new Date())
								.set(Temporary.column_number, oldTemp.getStr(Temporary.column_number)).set("dataStatus","1");
						if (!temp.update()) {
							log.debug("测算信息更新失败！！");
							throw new RuntimeException("测算信息更新失败!");
						}
					} else {
						temp.set("organIds", organids).set("treatment", treatment).set("gxsj", new Date());
						if (!temp.save()) {
							log.debug("测算信息保存失败！！");
							throw new RuntimeException("测算信息保存失败!");
						}
						//保存日护理综合查询（新顾客咨询人数）
						DailyNursingTotal  dnt = DailyNursingTotal.dao.getDnt(organids,new Date());
						if(dnt != null)
						{
							dnt.set(DailyNursingTotal.column_zxrs, dnt.getInt(DailyNursingTotal.column_zxrs)+1);
							if (!dnt.update()) {
								log.debug("更新日护理综合查询（新顾客咨询人数失败）！！");
								throw new RuntimeException("更新日护理综合查询（新顾客咨询人数失败）!");
							}
						}else
						{
							DailyNursingTotal dnt1= new DailyNursingTotal();
							dnt1.set(DailyNursingTotal.column_organids, organids)
								.set(DailyNursingTotal.column_date, ToolDateTime.format(new Date(), ToolDateTime.pattern_ymd))
								.set(DailyNursingTotal.column_zxrs, 1);
							if (!dnt1.save()) {
								log.debug("保存日护理综合查询（新顾客咨询人数失败）！！");
								throw new RuntimeException("保存日护理综合查询（新顾客咨询人数失败）!");
							}
						}
					
					}
					mm.put("treatment", treatment);

				} else {
					log.debug("输入的年龄，身高，体重有误，无法与标准体重进行测算，请重新输入！");
					// msg="输入的年龄，身高，体重有误，无法与标准体重进行测算，请重新输入！";
					// throw new
					// RuntimeException("输入的年龄，身高，体重有误，无法与标准体重进行测算，请重新输入！");
					msg = "输入的年龄，身高，体重有误，无法与标准体重进行测算，请重新输入！";
				}
			}

		}
		mm.put("msg", msg);
		return mm;
	}

	/**
	 * 获取介绍人门店
	 * 
	 * @param jsrPhone
	 */
	public RenderBean getJsrStore(String jsrPhone) {
		RenderBean result = new RenderBean();
		String orgSql = getSqlMy(Temporary.sqlId_selOrgByCusPhone);
//		Organization org = Organization.dao.findFirst(orgSql, jsrPhone, jsrPhone);
		Organization org = Organization.dao.findFirst(orgSql, jsrPhone);
		if (org != null) {
			result.setCode(ConstantRender.render_success_code);
			result.setMode(org);
			result.setMsg("2");
		} else {
			String orgSql2 = getSqlMy(Customer.sqlId_selOrgByCusPhone1);
			Organization org2 = Organization.dao.findFirst(orgSql2, jsrPhone, jsrPhone);
			if (org2 != null) {
				result.setCode(ConstantRender.render_success_code);
				result.setMode(org2);
				result.setMsg("1");
			} else {
				
				result.setCode(ConstantRender.render_error_code);
				result.setMsg("用户不存在！");
			}
		}
		return result;
}

	/**
	 * 保存顾客详细信息
	 * 
	 * @param temp
	 * @param cus
	 * @param cusDet
	 * @param cusAgr
	 */
	public RenderBean saveTempAndCus(Temporary temp, CustomerAgreement cusAgr, String delWeight,
			String targetWeight, String cudid, String chargePersion, String userIds) {
		String msg = "";
		String cusIds = "";

		List<Record> organnamelist = Db.find("SELECT `name` FROM sys_organization WHERE ids=?", cudid);
		String organname = organnamelist.get(0).get("name").toString();
		
		RenderBean result = new RenderBean();
		Temporary oldTemp = Temporary.dao.getTemporary(temp.getStr(Temporary.column_phone));
		int tre = cusAgr.getInt(CustomerAgreement.column_treatment);
		String scallCusIds = temp.getStr(Temporary.column_ids);
		
		//测算信息保存
		if (oldTemp != null) {
			oldTemp.set(Temporary.column_standWeight, cusAgr.getFloat(CustomerAgreement.column_std_weight));
			oldTemp.set(Temporary.column_treatment, tre + "");
			oldTemp.set(Temporary.column_targetWeight, targetWeight);
			oldTemp.set(Temporary.column_delWeight, delWeight);
			oldTemp.set(Temporary.column_weightDay, cusAgr.getInt(CustomerAgreement.column_target) + "");
			oldTemp.set(Temporary.column_cost, cusAgr.getDouble(CustomerAgreement.column_cost));
			oldTemp.set(Temporary.column_organIds, cudid);
			oldTemp.set(Temporary.column_loseReason, temp.getStr(Temporary.column_loseReason));
			oldTemp.set(Temporary.column_jdfs, temp.getStr(Temporary.column_jdfs));
			oldTemp.set(Temporary.column_jsrIds, temp.getStr(Temporary.column_jsrIds));
			oldTemp.set(Temporary.column_jsrName, temp.getStr(Temporary.column_jsrName));
			oldTemp.set(Temporary.column_jsrPhone, temp.getStr(Temporary.column_jsrPhone));
			oldTemp.set(Temporary.column_jsrorg, temp.getStr(Temporary.column_jsrorg));
			oldTemp.set(Temporary.column_jsrtype, temp.getStr(Temporary.column_jsrtype));
			oldTemp.set(Temporary.column_gkfl, temp.getStr(Temporary.column_gkfl));
			oldTemp.set(Temporary.column_gkfy, temp.getStr(Temporary.column_gkfy));
			oldTemp.set(Temporary.column_fzr, chargePersion);
			oldTemp.set(Temporary.column_jdr, temp.getStr(Temporary.column_jdr));
			oldTemp.set(Temporary.column_updateDate, new Date());
			oldTemp.set(Temporary.column_updateId, userIds);
			if (!oldTemp.update()) {
				log.debug("测算信息更新失败！！");
				throw new RuntimeException("测算信息更新失败!");
			}
			scallCusIds = oldTemp.getStr(Temporary.column_ids);
		} else {
			temp.set(Temporary.column_treatment, tre + "");
			temp.set(Temporary.column_standWeight, cusAgr.getFloat(CustomerAgreement.column_std_weight));
			temp.set(Temporary.column_targetWeight, targetWeight);
			temp.set(Temporary.column_delWeight, delWeight);
			temp.set(Temporary.column_weightDay, cusAgr.getInt(CustomerAgreement.column_target) + "");
			temp.set(Temporary.column_cost, cusAgr.getDouble(CustomerAgreement.column_cost));
			temp.set(Temporary.column_createDate, new Date());
			temp.set(Temporary.column_createId, userIds);
			temp.set(Temporary.column_fzr, chargePersion);
			if (!temp.save()) {
				log.debug("测算信息保存失败！！");
				throw new RuntimeException("测算信息保存失败!");
			}
			scallCusIds = temp.getStr(Temporary.column_ids);
		}
		
		//保存电话回访信息
		ScallVisit scall = new ScallVisit();
		scall.set("organIds", cudid)
		.set("subject", temp.getStr(Temporary.column_talk))
		.set("visitDate", new Date())
		.set("phone", temp.getStr(Temporary.column_phone))
		.set("isSatisfaction", temp.getStr(Temporary.column_gkfy))
		.set("jdr", temp.getStr(Temporary.column_jdr))
		.set("createId", userIds)
		.set("loseReason", temp.getStr(Temporary.column_loseReason))
		.set("gkfl", temp.getStr(Temporary.column_gkfl))
		.set("weight", temp.getFloat(Temporary.column_weight))
		.set("advice", temp.getStr(Temporary.column_talk))
		.set("visitType", 2)
		.set("createDate", new Date())
		.set("customerids",scallCusIds);
		if(!scall.save())
		{
			log.debug("电话回访信息保存失败！！");
			throw new RuntimeException("电话回访信息保存失败!");
		}
		
		// 如果测算信息的顾客分类ids等于code表成交顾客ids
		if (temp.getStr(Temporary.column_gkfl).equals(Code.cjCus_ids)) {
			Customer cus = new Customer();
			// 保存顾客登记信息
			String cids = ToolRandoms.getUuid(true);
			cus.set(Customer.column_ids, cids);
			cus.set(Customer.column_userName, temp.getStr(Temporary.column_phone));
			try {
				byte[] salt = ToolPbkdf2.generateSalt();// 密码盐
				byte[] encryptedPassword = ToolPbkdf2.getEncryptedPassword("123456", salt);
				cus.set(Customer.column_salt, Base64.encodeBase64String(salt));
				cus.set(Customer.column_password, Base64.encodeBase64String(encryptedPassword));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// 通过当前机构id获取机构编码
			// String cuoBh=BentryRegisterService.getOrgBh(cudid);
			// 获取当前机构顾客的编号最大（也就是最新进店的顾客会员编号）
			// 通过机构编号模糊查询
			// String par="%"+cuoBh+"%";
			String chybh = "000001";
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("column", Customer.column_organIds);
			String sql = getSqlByBeetl(Customer.sqlId_column, param);
			List<Customer> clist = Customer.dao.find(sql, cudid);
			ArrayList<Integer> numList = new ArrayList<Integer>();
			if (clist != null && clist.size() > 0) {
				for (Customer cuss : clist) {
					String hybh = cuss.getStr(Customer.column_hybh);
					int n = Integer.parseInt(hybh);
					numList.add(n);
				}
				int a = Collections.max(numList);
				chybh = String.format("%06d", a + 1);
			}
			
			cus.set(Customer.column_hybh, chybh).set(Customer.column_organIds, cudid)
					.set(Customer.column_name, temp.getStr(Temporary.column_name))
					.set(Customer.column_age, temp.getInt(Temporary.column_age))
					.set(Customer.column_sex, temp.getStr(Temporary.column_sex))
					.set(Customer.column_phone, temp.getStr(Temporary.column_phone))
					.set(Customer.column_registtime, new Date()).set(Customer.column_lastlogintime, new Date())
					.set(Customer.column_createDate, new Date())
					.set(Customer.column_createId, userIds)
					.set(Customer.column_state, "1");
			if (!cus.save()) {
				log.debug("顾客信息保存失败！！");
				throw new RuntimeException("顾客信息保存失败!");
			}
			cusIds = cus.getStr(Customer.column_ids);
			CustomerDetail cusDet = new CustomerDetail();
			String cusDetids = ToolRandoms.getUuid(true);
			cusDet.set(CustomerDetail.column_ids, cusDetids)
					.set(CustomerDetail.column_organName, organname)
					.set(CustomerDetail.column_createId, userIds)
					.set(CustomerDetail.column_phone, cus.getStr(Customer.column_phone))
					.set(CustomerDetail.column_name, cus.getStr(Customer.column_name))
					.set(CustomerDetail.column_hybh, cus.getStr(Customer.column_hybh))
					.set(CustomerDetail.column_sex,  cus.getStr(Customer.column_sex))
					.set(CustomerDetail.column_age,  cus.getInt(Customer.column_age))
					.set(CustomerDetail.column_username, cus.getStr(Customer.column_userName))
					.set(CustomerDetail.column_standardWeight, cusAgr.get(CustomerAgreement.column_std_weight))
					.set(CustomerDetail.column_organIds, cus.getStr(Customer.column_organIds))
					.set(CustomerDetail.column_customerIds, cus.getStr(Customer.column_ids))
					.set(CustomerDetail.column_height, temp.getInt(Temporary.column_height))
					.set(CustomerDetail.column_firstWeight, temp.getFloat(Temporary.column_weight))
					.set(CustomerDetail.column_firstDate, new Date())
					.set(CustomerDetail.column_createDate, new Date())
					.set(CustomerDetail.column_minWeight,temp.getFloat(Temporary.column_weight))
					.set(CustomerDetail.column_minDate, new Date())
					.set(CustomerDetail.column_nowWeight, temp.getFloat(Temporary.column_weight))
					.set(CustomerDetail.column_toStoreDate, new Date())
					.set(CustomerDetail.column_delWeight, delWeight)
					.set(CustomerDetail.column_targetWeight, targetWeight)
					.set(CustomerDetail.column_type, temp.getStr(Temporary.column_jdfs))
					.set(CustomerDetail.column_jsrIds, temp.getStr(Temporary.column_jsrIds))
					.set(CustomerDetail.column_jsrName, temp.getStr(Temporary.column_jsrName))
					.set(CustomerDetail.column_jsrorg, temp.getStr(Temporary.column_jsrorg))
					.set(CustomerDetail.column_jsrPhone, temp.getStr(Temporary.column_jsrPhone))
					.set(CustomerDetail.column_jsrtype, temp.getStr(Temporary.column_jsrtype))
					.set(CustomerDetail.column_createDate, new Date())
					.set(CustomerDetail.column_createId, userIds)
					.set(CustomerDetail.column_sjtreatment,cusAgr.getInt(CustomerAgreement.column_treatment)+"")
					.set(CustomerDetail.column_chargePersion, chargePersion);
					
		

			// 根据疗程数求出结束的日期
			Calendar cal = Calendar.getInstance();
			cal.add(cal.MONTH, Integer.parseInt(cusAgr.get("target").toString()));
			SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			String lastMonth = dft.format(cal.getTime());

			// 保存总目标汇总表
			DelWeiTargetSum delWeiT = new DelWeiTargetSum();
			delWeiT.set(DelWeiTargetSum.column_ids, delWeiT).set(DelWeiTargetSum.column_targetName, "总目标")
					.set(DelWeiTargetSum.column_delWei, delWeight).set(DelWeiTargetSum.column_targetWei, targetWeight)
					.set(DelWeiTargetSum.column_customerIds, cus.get("ids").toString())
					.set(DelWeiTargetSum.column_startWei, temp.get("weight").toString())
					.set(DelWeiTargetSum.column_createId, userIds).set(DelWeiTargetSum.column_createDate, new Date())
					.set(DelWeiTargetSum.column_endTime, lastMonth).set(DelWeiTargetSum.column_startTime, new Date());

			if (!delWeiT.save()) {
				log.debug("顾客总目标信息保存失败！");
				throw new RuntimeException("顾客总目标信息保存失败");
			}

			// 通过当前机构id获取机构编码
			String cuoBh = BentryRegisterService.getOrgBh(cudid);

			// 获取协议编号
			String bh = BentryRegisterService.getBH(cuoBh, cusAgr.getInt(CustomerAgreement.column_treatment),chybh,null);

			if(tre==1){
				cusAgr.set(CustomerAgreement.column_codeIds, Code.ylcdsh_ids);
				cusDet.set(CustomerDetail.column_treatmentName, Code.ylcdsh_ids);
			}else{
				cusDet.set(CustomerDetail.column_treatmentName,  Code.bzlc_ids);
				cusAgr.set(CustomerAgreement.column_codeIds, Code.bzlc_ids);
			}
			cusAgr.set(CustomerAgreement.column_customerID, cus.getStr(Customer.column_ids))
					.set(CustomerAgreement.column_organIds, cudid).set(CustomerAgreement.column_bh, bh)
					.set(CustomerAgreement.column_before_weight, temp.getFloat(Temporary.column_weight))
					.set(CustomerAgreement.column_after_weight, targetWeight).set(CustomerAgreement.column_isPay, "0")
					.set(CustomerAgreement.column_createId, userIds).set(CustomerAgreement.column_createDate, new Date())
					.set(CustomerAgreement.column_time, new Date()).set(CustomerAgreement.column_state, "1");

			if (!cusAgr.save()) {
				log.debug("顾客协议保存失败！！");
				throw new RuntimeException("顾客协议保存失败!");
			}
			cusDet.set(CustomerDetail.column_agreementBH,  bh)
			.set(CustomerDetail.column_agreementIds,cusAgr.getStr(CustomerAgreement.column_ids));
			if (!cusDet.save()) {
				log.debug("顾客详细信息保存失败！！");
				throw new RuntimeException("顾客详细信息保存失败!");
			}
			//保存日护理综合查询表（新顾客成交人数，新顾客转介绍成交人数，新顾客宣传成交人数，新顾客自然进店成交人数，新顾客成交率，新顾客应减斤数）
			
			
			DailyNursingTotal  dnt = DailyNursingTotal.dao.getDnt(cudid,new Date());
			if(dnt != null)
			{
				dnt.set(DailyNursingTotal.column_cjrs, dnt.getInt(DailyNursingTotal.column_cjrs)+1);
				if(temp.getStr(Temporary.column_jdfs).equals(Code.zjs_ids))//如果是转介绍
				{
					dnt.set(DailyNursingTotal.column_zjscjrs, dnt.getInt(DailyNursingTotal.column_zjscjrs)+1);
				}else if(temp.getStr(Temporary.column_jdfs).equals(Code.xc_ids))
				{
					dnt.set(DailyNursingTotal.column_xccjrs, dnt.getInt(DailyNursingTotal.column_xccjrs)+1);
				}else
				{
					dnt.set(DailyNursingTotal.column_zrjdcjrs, dnt.getInt(DailyNursingTotal.column_zrjdcjrs)+1);
				}
				double  cjl = ((double)dnt.getInt(DailyNursingTotal.column_cjrs))/((double)dnt.getInt(DailyNursingTotal.column_zxrs));
				dnt.set(DailyNursingTotal.column_xgkCjl,new DecimalFormat("#.00").format(cjl*100))
					.set(DailyNursingTotal.column_xgkYjjs, dnt.getDouble(DailyNursingTotal.column_xgkYjjs)+Double.parseDouble(delWeight));
				if (!dnt.update()) {
					log.debug("更新日护理综合查询失败！！");
					throw new RuntimeException("更新日护理综合查询失败!");
				}	
			}
			
			msg = ConstantRender.render_success_code;
		} else {
			msg = "1";
		}
		result.getMap().put("msg", msg);
		result.getMap().put("cusIds", cusIds);
		return result;
	}

	/**
	 * 用手机号搜索顾客信息
	 */
	public Map<String, Object> phoneSearch(String name, String phone, String orgid) {
		Map<String, Object> mm = new HashMap<>();
		Record r = null;
		Map<String, Object> queryParam = new HashMap<String, Object>();
		queryParam.put("phone", phone);
		queryParam.put("orgid", orgid);
		queryParam.put("name", name);

		String sql1 = "select * from sb_customer_temporary where organIds = ? and  (phone = ? or name = ?)and dataStatus=1  ";
		Temporary temporary = Temporary.dao.findFirst(sql1, orgid, phone, name);
		if (temporary != null) {
			String gkfl = temporary.getStr(Temporary.column_gkfl);
			if (gkfl.equals("607f10b77f4d4b908104e990f366a334")) {
				mm.put("msg", "该顾客已为成交顾客");
			} else {
				String visitsql = "SELECT IFNULL(count(*),0)  AS count FROM sb_customer_scallvisit WHERE  customerids = ? and visitType = 1";
				Record f = Db.findFirst(visitsql, temporary.getStr(Temporary.column_ids));
				mm.put("callvisitcount", f.get("count").toString());
				visitsql = "SELECT IFNULL(count(*),0)  AS count FROM sb_customer_scallvisit WHERE  customerids = ? and visitType = 2";
				f = Db.findFirst(visitsql, temporary.getStr(Temporary.column_ids));
				mm.put("toshopvisitcount", f.get("count").toString());

				Temporary r1 = temporary;
				mm.put("temporaryCustomerIds", r1.get("ids"));
				mm.put("name", r1.get("name"));
				mm.put("sex", r1.get("sex"));
				mm.put("phone", r1.get("phone"));
				mm.put("age", r1.get("age"));
				mm.put("weight", r1.get("weight"));
				mm.put("height", r1.get("height"));

				mm.put("delWeight", r1.get("delWeight"));
				mm.put("treatment", r1.get("treatment"));
				mm.put("targetWeight", r1.get("targetWeight"));
				mm.put("weightDay", r1.get("weightDay"));
				mm.put("cost", r1.get("cost"));
				mm.put("standWeight", r1.get("standWeight"));

				mm.put("jdfs", r1.get("jdfs"));
				mm.put("loseReason", r1.get("loseReason"));

				mm.put("jdr", r1.get("jdr"));
				mm.put("gkfy", r1.get("gkfy"));
				mm.put("gkfl", r1.get("gkfl"));
				
				String sql = getSqlMy("sb.temporary.querypeople");
				List<Record> result = Db.find(sql,  r1.get("ids"), 2, orgid);
				if(result!=null&&result.size()>0){
					mm.put("resultddfw", result);
				}
				
				result = Db.find(sql,  r1.get("ids"), 1, orgid);
				if(result!=null&&result.size()>0){
					mm.put("resultdhhw", result);
				}
				
				mm.put("msg", "200");
			}
		} else {
			mm.put("msg", "该顾客无本店测算信息");
		}
		return mm;
	}

	// /**
	// * 获取测算结果
	// */
	// public static String calculate(Float stdWeight, Float weight){
	//// float stdWeight = getStdWeight(sex, height, age);
	// String result;
	// if(stdWeight!=0)
	// {
	// float differ_weight = weight - stdWeight;
	// BigDecimal b = new BigDecimal(differ_weight);
	// float differ_weight1 = b.setScale(2,
	// BigDecimal.ROUND_HALF_UP).floatValue();
	// if(differ_weight<0)
	// {
	// result="0";
	// }else
	// {
	// result = "您的标准体重为" + stdWeight + "斤，实际测重为"
	// + weight + "斤，相差" + differ_weight1 + "斤，建议您选择" + getTreatment(weight,
	// stdWeight) + "疗程。";
	// }
	// }else
	// {
	// result="输入的年龄，身高，体重有误，无法与标准体重进行测算，请重新输入！";
	// }
	// return result;
	// }
	/**
	 * 测算获得标准体重
	 * 
	 * @param sex
	 * @param height
	 * @param age
	 * @return 斤
	 */
	public static float getStdWeight(String sex, int height, int age) {
		return StdWeightModel.me.getStdWeight(sex, height, age) * 2;
	}

	/**
	 * 测算获得疗程数
	 * 
	 * @param weight
	 * @param stdWeight
	 * @return
	 */
	public static int getTreatment(float differ_weight) {
		// float differ_weight = weight - stdWeight;
		if(differ_weight<0){
			return 0;
		}else{
			int lcs = (int)Math.ceil(differ_weight/10);
			return lcs;
		}
		
//		if (0 < differ_weight && differ_weight <= 10) {
//			return 1;
//		} else if (10 < differ_weight && differ_weight <= 20) {
//			return 2;
//		} else if (20 < differ_weight && differ_weight <= 30) {
//			return 3;
//		} else if (30 < differ_weight && differ_weight <= 40) {
//			return 4;
//		} else if (40 < differ_weight && differ_weight <= 50) {
//			return 5;
//		} else if (differ_weight <= 0) {
//			return 0;
//		} else {
//			return 6;
//		}
	}

	/**
	 * 根据编号查询数据
	 * 
	 * @param number编号
	 * @param obj（上一条下一条标识）
	 * @return
	 */
	public Temporary selOther(String number, String obj, String organids) {
		int n = Integer.parseInt(number.substring(number.length() - 3, number.length()));
		// String num="1705140100";
		// 获取当月
		SimpleDateFormat df = new SimpleDateFormat("yyMM");
		String date = df.format(new Date());
		// 获取当前代理商门店编号
		String dlmdBH = BentryRegisterService.getOrgBh(organids);
		String num = date + dlmdBH;
		if (obj != null) {
			if (obj.equals("1")) {
				log.debug("获取上一条数据");
				num += String.format("%03d", n - 1);
			}
			if (obj.equals("2")) {
				log.debug("获取下一条数据");
				num += String.format("%03d", n + 1);
			}
		} else {
			num = number;
		}

		String sql = getSqlMy(Temporary.sqlId_selTemByNum);
		Temporary tem = Temporary.dao.findFirst(sql, num);
		Temporary tem1 = Temporary.dao.findFirst(sql, number);
		if (tem != null || tem1 != null) {
			return tem;
		} else {
			// Temporary tem1=Temporary.dao.findFirst(sql,number);
			return null;
		}

	}

	/*
	 * 今日测算查询
	 */
	public List<Record> todaymeasure(String organids, String todaydate) {
		String sql = getSqlMy("sb.temporary.todaymeasure");
		List<Record> result = Db.find(sql, organids, todaydate);
		return result;
	}

	public List<Temporary> getCusInfo(String orgid) {
		String sql1 = "select * from sb_customer_temporary where organIds = ? and dataStatus=1 and gkfl != '607f10b77f4d4b908104e990f366a334'";
		List<Temporary> cbis = Temporary.dao.find(sql1, orgid);
		return cbis;
	}

	public List<Temporary> getCusAndUserInfo() {
		String sql1 = " (select ids, `name`,phone,organIds,sex  from  sb_customer_temporary  where dataStatus=1)UNION(select ids,`name`,mobile,organizationids,organizationids from sys_user)";
		List<Temporary> cbis = Temporary.dao.find(sql1);
		return cbis;
	}
	
	

}
